// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode');
const path = require('path');
const utils = require("./utils");

const zjs = require('./transpile/zjs');
const zhtm = require('./transpile/zhtm');
const zcss = require('./transpile/zcss');
const zless = require('./transpile/zless');
const { transCEfuncs } = require('./transpile/transformCtoEfuncs');

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed

/**
 * @param {vscode.ExtensionContext} context
 */
function activate(context) {

	// Use the console to output diagnostic information (console.log) and errors (console.error)
	// This line of code will only be executed once when your extension is activated
	console.log('中文开发扩展 "zwfe" 现已激活!');

	// The command has been defined in the package.json file
	// Now provide the implementation of the command with  registerCommand
	// The commandId parameter must match the command field in package.json
	// let disposable = vscode.commands.registerCommand('zwfe.helloZWFE', function () {
	// 	// The code you place here will be executed every time your command is executed

	// 	// Display a message box to the user
	// 	vscode.window.showInformationMessage('欢迎使用中文 Web 开发语言!');
	// });

	// context.subscriptions.push(disposable);

	// const activeEditor = vscode.window.activeTextEditor;
	// if (activeEditor) {
	// 	const document = activeEditor.document;
	// }

	function fileType (filename) {
		let index1 = filename.lastIndexOf(".");
		let index2 = filename.length;
		let tp = filename.substring(index1, index2);
		if ([".js", ".ts", ".html", ".css", ".less"].includes(tp)) {
			tp = filename.substring(index1-2, index2);
			return tp;
		}
		return tp;
	};

	// transpile .z.* files on save when file is dirty
	const didSaveEvent = vscode.workspace.onDidSaveTextDocument((document) => {
		// console.log(document.fileName);
		const fileSuffix = fileType(document.fileName);
		// console.log(fileSuffix);
		if ([".z.js", ".z.ts", ".z.html", ".z.css", ".z.less", ".v.html"].includes(fileSuffix)) {
			let zfilePath = path.dirname(document.fileName);
			let baseFilenameDotZ = path.parse(document.fileName).name;
			let baseFilename = baseFilenameDotZ.substring(0, baseFilenameDotZ.lastIndexOf("."));
			let zFileContent = document.getText();

			switch(fileSuffix) {
				case ".z.js":
				case ".z.ts":
					const jsFile = path.join(zfilePath, baseFilename + ".js");
					let script = zjs.transpile(zFileContent);
					let jsFileContent;
					try {						
						jsFileContent = transCEfuncs(script);
					} catch (error) {
						console.log(error);
					}
					// console.log(jsFileContent);
					utils.writeFileContents(jsFile, jsFileContent);
					// zjs.zjsTranspile(jsFile, zFileContent);
					break;
				case ".z.html":
					const htmlFile = path.join(zfilePath, baseFilename + ".html");
					try {						
						zhtm.zhtmTranspile(htmlFile, zFileContent);
					} catch (error) {
						console.log(error);
					}
					break;
				case ".v.html":
					const vueFile = path.join(zfilePath, baseFilename + ".vue");
					try {						
						zhtm.zhtmTranspile(vueFile, zFileContent);
					} catch (error) {
						console.log(error);
					}
					break;
				case ".z.css":
					const cssFile = path.join(zfilePath, baseFilename + ".css");
					try {						
						zcss.zcssTranspile(cssFile, zFileContent);
					} catch (error) {
						console.log(error);
					}
					break;
				case ".z.less":
					const lessFile = path.join(zfilePath, baseFilename + ".css");
					try {						
						zless.zlessTranspile(lessFile, zFileContent);
					} catch (error) {
						console.log(error);
					}
					break;
				default:
					break;
			}
		}
	});

	context.subscriptions.push(didSaveEvent);

	// 之前的 HD...DH 做法, 不久后删除
	// let timeout = undefined;

	// const HDDHDecorationType = vscode.window.createTextEditorDecorationType({
	// 	textDecoration: "underline"
	// });

	// let activeEditor = vscode.window.activeTextEditor;

	// function updateDecorations() {
	// 	if (!activeEditor) {
	// 		return;
	// 	}
	// 	const regEx = /HD[a-zA-Z0-9_]+DH/g;
	// 	const text = activeEditor.document.getText();
	// 	const HDDHs = [];
	// 	let match;
	// 	while ((match = regEx.exec(text))) {
	// 		const startPos = activeEditor.document.positionAt(match.index);
	// 		const endPos = activeEditor.document.positionAt(match.index + match[0].length);
	// 		const decoration = { range: new vscode.Range(startPos, endPos), hoverMessage: '就当我不存在' };
	// 		// if (match[0].length < 3) {
	// 			HDDHs.push(decoration);
	// 		// }
	// 	}
	// 	activeEditor.setDecorations(HDDHDecorationType, HDDHs);
	// }

	// function triggerUpdateDecorations() {
	// 	if (timeout) {
	// 		clearTimeout(timeout);
	// 		timeout = undefined;
	// 	}
	// 	timeout = setTimeout(updateDecorations, 500);
	// }

	// if (activeEditor) {
	// 	triggerUpdateDecorations();
	// }

	// vscode.window.onDidChangeActiveTextEditor(editor => {
	// 	activeEditor = editor;
	// 	if (editor) {
	// 		triggerUpdateDecorations();
	// 	}
	// }, null, context.subscriptions);

	// vscode.workspace.onDidChangeTextDocument(event => {
	// 	if (activeEditor && event.document === activeEditor.document) {
	// 		triggerUpdateDecorations();
	// 	}
	// }, null, context.subscriptions);
}

// this method is called when your extension is deactivated
function deactivate() {}

module.exports = {
	activate,
	deactivate
}
